package org.moca.activity;

/*
 import android.R;
 import android.app.Activity;
 import android.os.Bundle;
 */

import java.util.Timer;
import java.util.TimerTask;

import org.moca.Constants;
import org.moca.R;
import org.moca.R.layout;
import org.moca.service.BackgroundUploader;
import org.moca.task.CheckCredentialsTask;
import org.moca.task.ValidationListener;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Toast;

public class sanaLogin extends Activity {
	/** Called when the activity is first created. */
	private EditText username = null;
	private EditText password = null;
	private Button login;
	boolean logmark;
	int counter = 3;
	private CheckCredentialsTask mCredentialsTask2;
	private BackgroundUploader mUploadService = null;
	private static final int DIALOG_INCORRECT_PASSWORD = 0;
	private static final int DIALOG_NO_CONNECTIVITY = 1;
	private static final int DIALOG_NO_PHONE_NAME = 2;
	final Timer timer = new Timer();
	TextView usernametv, passwordtv;

	private TimerTask onComplete;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.sana);

		// TODO Auto-generated method stub
		username = (EditText) findViewById(R.id.editText1);
		usernametv = (TextView) findViewById(R.id.editText1);
		password = (EditText) findViewById(R.id.editText2);
		passwordtv = (TextView) findViewById(R.id.editText2);

		login = (Button) findViewById(R.id.button1);
	}

	public void login(View view) {

		final CheckCredentialsTask task = new CheckCredentialsTask();
		task.setValidationListener(new CredentialsValidatedListener());
		mCredentialsTask2 = (CheckCredentialsTask) task.execute(this);

	}

	public void settings(View view) {
		Intent j = new Intent(sanaLogin.this,
				org.moca.activity.SettingsLogin.class);
		startActivity(j);

	}

	public void test(View view) {
		SharedPreferences sharedPreferences = getSharedPreferences("login",
				Context.MODE_PRIVATE);
		String storedUser = sharedPreferences.getString("storedUser",
				Constants.DEFAULT);
		String storedPass = sharedPreferences.getString("storedPass",
				Constants.DEFAULT);
		usernametv.setText(storedUser);
		passwordtv.setText(storedPass);
	}

	private class CredentialsValidatedListener implements ValidationListener {
		/**
		 * Called when CheckCredentialsTask completes
		 */
		public void onValidationComplete(int validationResult) {
			switch (validationResult) {
			case (CheckCredentialsTask.CREDENTIALS_NO_CONNECTION):
				if (!isFinishing())
					showDialog(DIALOG_NO_CONNECTIVITY);
				break;
			case (CheckCredentialsTask.CREDENTIALS_INVALID):
				if (mUploadService != null) {
					mUploadService.onCredentialsChanged(false);
				}
				break;
			case (CheckCredentialsTask.CREDENTIALS_VALID):
				if (mUploadService != null) {
					Intent x = new Intent(sanaLogin.this, org.moca.activity.Moca.class);
					startActivity(x);
					mUploadService.onCredentialsChanged(true);
				}
				SharedPreferences sharedPreferences = getSharedPreferences(
						"login", Context.MODE_PRIVATE);
				SharedPreferences.Editor prefEdit = sharedPreferences.edit();
				prefEdit.putString("storedUser", username.getText().toString());
				prefEdit.putString("storedPass", password.getText().toString());

				prefEdit.commit();
				Intent i = new Intent(sanaLogin.this, org.moca.activity.Moca.class);
				startActivity(i);
				break;
			}
		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_INCORRECT_PASSWORD:
			return new AlertDialog.Builder(this)
					.setTitle("Error!")
					.setMessage(
							getString(R.string.dialog_incorrect_credentials))
					.setPositiveButton(
							getString(R.string.general_change_settings),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {

									// decrement attempt counter
									counter--;

									// disable login on 3 failures
									if (counter <= 0) {
										login.setEnabled(false);

										login.postDelayed(new Runnable() {
											public void run() {
												login.setVisibility(View.VISIBLE);
												login.setEnabled(true);
											}
										}, 7000);
									}

									setResult(RESULT_OK, null);
									dialog.dismiss();
								}
							})
					.setCancelable(true)
					.setNegativeButton(getString(R.string.general_cancel),
							new OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									setResult(RESULT_CANCELED, null);
									dialog.dismiss();
								}
							}).create();
		case DIALOG_NO_CONNECTIVITY:
			return new AlertDialog.Builder(this)
					.setTitle(getString(R.string.general_error))
					.setMessage(
							getString(R.string.dialog_no_network_login_version))
					.setPositiveButton(getString(R.string.general_ok),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									// Dismiss dialog and return to settings
									noConnectionValidation();
									setResult(RESULT_OK, null);
									dialog.dismiss();
								}
							}).create();
		case DIALOG_NO_PHONE_NAME:
			return new AlertDialog.Builder(this)
					.setTitle(getString(R.string.general_error))
					.setMessage(getString(R.string.dialog_no_phone_name))
					.setPositiveButton(
							getString(R.string.general_change_settings),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									setResult(RESULT_OK, null);
									dialog.dismiss();
								}
							})
					.setCancelable(true)
					.setNegativeButton(getString(R.string.general_cancel),
							new OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									setResult(RESULT_CANCELED, null);
									dialog.dismiss();
								}
							}).create();
		}
		return null;
	}

	public void noConnectionValidation() {
		SharedPreferences sharedPreferences = getSharedPreferences("login",
				Context.MODE_PRIVATE);

		String storedUser = sharedPreferences.getString("storedUser",
				Constants.DEFAULT);
		String storedPass = sharedPreferences.getString("storedPass",
				Constants.DEFAULT);

		String currentUser = username.getText().toString();
		String currentPass = password.getText().toString();

		if (username.getText().toString().equals("")
				|| password.getText().toString().equals("")) {
			Toast.makeText(
					getApplicationContext(),
					"Please input username/password, " + (counter)
							+ " attempt/s left.", Toast.LENGTH_SHORT).show();
			// decrement attempt counter
			// counter--;

		}

		else if (username.getText().toString().equals(storedUser)
				&& password.getText().toString().equals(storedPass)) {
			// reset attempt counter
			counter = 3;

			// redirect to main menu
			Intent i = new Intent(sanaLogin.this, org.moca.activity.Moca.class);
			startActivity(i);
		} else {
			// display error message
			Toast.makeText(getApplicationContext(),
					"Wrong Credentials, " + (counter - 1) + " attempt/s left.",
					Toast.LENGTH_SHORT).show();

			// decrement attempt counter
			counter--;

			// disable login on 3 failures
			if (counter <= 0) {
				login.setEnabled(false);

				// timer.schedule(onComplete, 0, 2000);
				login.postDelayed(new Runnable() {
					public void run() {
						login.setVisibility(View.VISIBLE);
						login.setEnabled(true);
						counter = 3;
					}
				}, 7000);

			}

		}

	}

}
